import axios from 'axios'
import { EType, genDefaultConfig, createPortEdge, createDocument, mouseClickCreateRoundEdge, createAttrsAndMarkup, createAttrsAndMarkupForEntrance, createAttrsAndMarkupForElectrical } from './config.js'
import './register.js'
import _, { round } from 'lodash'

const graphEvent = (graph, vm) => {

  // 生成时
  graph.on('cell:added', ({ cell, options }) => {
    if (!vm.edit) return
    graph.cleanSelection()
    graph.clearTransformWidgets()
    vm.activeTab = null
    vm.selectedCell = cell
    // 如果不是stencil拖动出来的元素，不需要重新设置（处理复制出来重新设置的问题）
    if (!options.stencil) return

    vm.config = genDefaultConfig()

    vm.node = cell
    const { type } = cell.data
    // 直线
    if (type === EType.RoundEdge.alias) {
      cell.attr('body/fill', 'none')
      cell.attr('body/stroke', 'none')
      cell.attr('text/text', '')
      cell.prop('data/type','' )

      const { x, y } = cell.position()
      const cell2 = graph.addNode(
        {
          ...cell.getProp(),
          id: cell.id + 'copy',
          x: x + 100,
        }
      )
      graph.addEdge({
        source: {
          cell: cell,
          port: 'port1'
        },
        target: {
          cell: cell2,
          port: 'port1', // 连接桩 ID
        },
        connector: 'rounded',
        attrs: {
          line: {
            stroke: '#31dca0',
            targetMarker: null,
          },
        },
        tools: {
          name: 'vertices',
          args: {
            attrs: {
              fill: '#31dca0',
            },
            modifiers: 'ctrl',
          },
          snapRadius: 5,
          removeRedundancies: false,
        },
        data: {
          connector: 'rounded', // rounded：直线 smooth：曲线
          strokeWidth: 2,
          tag: 'roundEdge1',
          index: 0,
          type: EType.RoundEdge.alias,
        }
      })
    }
    // 曲线
    else if (type === EType.SmoothEdge.alias) {
      cell.attr('body/fill', 'none')
      cell.attr('body/stroke', 'none')
      cell.attr('text/text', '')
      cell.prop('data/type','' )

      const { x, y } = cell.position()
      const cell2 = graph.addNode(
        {
          ...cell.getProp(),
          id: cell.id + 'copy',
          x: x + 100,
        }
      )
      graph.addEdge({
        source: {
          cell: cell,
          port: 'port1'
        },
        target: {
          cell: cell2,
          port: 'port1', // 连接桩 ID
        },
        connector: 'smooth',
        attrs: {
          line: {
            stroke: '#31dca0',
            targetMarker: null,
          },
        },
        tools: {
          name: 'vertices',
          args: {
            attrs: {
              fill: '#31dca0',
            },
            modifiers: 'ctrl',
          },
          snapRadius: 5,
          removeRedundancies: false,
        },
        data: {
          connector: 'smooth',
          strokeWidth: 2,
          tag: 'smoothEdge1',
          index: 0,
          type: EType.SmoothEdge.alias,
        }
      })

    }

    localStorage.setItem('$graph_config', JSON.stringify(vm.config))
  })

  // 单击时
  graph.on('cell:click', ({ x, y, cell }) => {
    console.log(cell)
    if (!vm.edit) return

    const { data } = cell
    if (!data || !vm.config[data.type]) return;
    vm.activeTab = data.type
    vm.config[data.type] && Object.assign(vm.config[data.type], data, {
      range: [data.start, data.end],
    })

    vm.selectedCell = cell
  })

  graph.on('blank:click', ({ x, y, e, view }) => {
    if (!vm.edit) return

    vm.activeTab = null
    vm.selectedCell = null
  })


  graph.on('node:rotated', ({ node }) => {
    node.setProp('data', {
      ...node.prop('data'),
      rotate: node.getProp('angle') + 90
    })
    vm.config[node.data.type].rotate = node.getProp('angle') + 90
  })

  // 这里是可以从线条拉出新的线条
  // let roundEdges = []
  // let smoothEdges = []
  // let isCtrlPressed = false;
  // graph.bindKey('ctrl', () => {
  //   if (isCtrlPressed) return;
  //   isCtrlPressed = true;
  //   roundEdges = graph.getCells().filter(cell => cell.data?.type === EType.RoundEdge.alias)
  //   smoothEdges = graph.getCells().filter(cell => cell.data?.type === EType.SmoothEdge.alias)

  //   for (let edge of roundEdges) {
  //     if (!edge.ports) continue
  //     edge.portProp('port1', 'attrs/circle/magnet', true)
  //   }

  //   for (let edge of smoothEdges) {
  //     if (!edge.ports) continue
  //     edge.portProp('port1', 'attrs/circle/magnet', true)
  //   }

  // }, 'keydown')

  // graph.bindKey('ctrl', () => {
  //   for (let edge of roundEdges) {
  //     if (!edge.ports) continue
  //     edge.portProp('port1', 'attrs/circle/magnet', false)
  //   }

  //   for (let edge of smoothEdges) {
  //     if (!edge.ports) continue
  //     edge.portProp('port1', 'attrs/circle/magnet', false)
  //   }
  //   roundEdges = []
  //   smoothEdges = []
  //   isCtrlPressed = false
  // }, 'keyup')

  // ctrl+a全选
  graph.bindKey(['meta+a', 'ctrl+a'], () => {
    const cells = graph.getCells()
    console.log(cells)
    graph.select(cells)
    return false
  })

  graph.bindKey(['meta+c', 'ctrl+c'], () => {
    const cells = graph.getSelectedCells()
    if (cells.length) {
      graph.copy(cells, { deep: true })
    }
    return false
  })
  graph.bindKey(['meta+x', 'ctrl+x'], () => {
    const cells = graph.getSelectedCells()
    if (cells.length) {
      graph.cut(cells)
    }
    return false
  })
  graph.bindKey(['meta+v', 'ctrl+v'], () => {
    if (!graph.isClipboardEmpty()) {
      const cells = graph.paste({ offset: 32 })
      console.log(cells)
      graph.cleanSelection()
      graph.select(cells)
    }
    return false
  })
  graph.bindKey(['meta+z', 'ctrl+z'], () => {
    if (graph.canUndo()) {
      graph.undo()
    }
    return false
  })
  // watch zoom
  let zoomRatio = window.devicePixelRatio
  // 判断是否按下了ctrl键并且滚动了鼠标滚轮
  document.addEventListener(
    'wheel',
    function (event) {
      if (event.ctrlKey || event.altKey) {
        if (event.deltaY < 0) {
          zoomRatio += 0.1
          graph.zoomTo(zoomRatio)
        } else {
          zoomRatio -= 0.1
          graph.zoomTo(zoomRatio)
        }
        event.preventDefault() // 阻止页面的缩放行为
      }
    },
    { passive: false }
  )

}

export default graphEvent
